//
//  MNDCreditListViewController.m
//  minidai
//
//  Created by Vitas on 2018/8/3.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDCreditListViewController.h"
#import "MNDCreditListCell.h"
#import "UIImage+JKColor.h"
#import "MNDFinanceListModel.h"
#import "SYRefreshControl.h"
#import "MNDCreditorDetaiRootViewController.h"
#import "MNDCreditorHRdetailViewController.h"

@interface MNDCreditListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//占位图
@property (strong, nonatomic) UIView *placeHolderMaskView;
//债权转让数据页码
@property (assign, nonatomic) NSInteger creditorPageNumber;

//数据源
@property(nonatomic, strong) NSMutableArray *dataArray;

/**
 债转标网络请求id
 */
@property (nonatomic, strong) NSString *creditorNetworkId;

@property (strong,nonatomic) MNDFinanceListModel *financeListModel;

@end

@implementation MNDCreditListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self setupUI];

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.creditorNetworkId = nil;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.creditorNetworkId) {
        [XMCenter cancelRequest:self.creditorNetworkId];
    }
    
}

#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark -搭建界面
- (void)setupUI {
    WeakSelf(self);
    
    [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportALl beginRefresh:YES timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        
        [weakself loadData:YES];

    } loadMoreBlock:^{

        [weakself loadData:NO];
        
    }];
    
    self.tableView.estimatedRowHeight = 44.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
    [self creatMaskView];
    
}

#pragma mark - 数据加载
- (void)loadData:(BOOL)isPullDown {
    
    __weak typeof(self) weakSelf = self;
    //请求参数
    NSDictionary *parametersDict;
    //如果下拉
    if (isPullDown) {//展示第一页数据
        _creditorPageNumber = 1;
    }else {//上拉加载后面几页数据
        
        _creditorPageNumber++;
        
    }
    parametersDict = @{@"perpage":@(_creditorPageNumber),
                       @"pagesize":@"10"
                       };
    
    NSDictionary *params = [MNDSign signedParamWithDict:parametersDict];
    //请求债权转让数据
    self.creditorNetworkId = [APIManager sendRequestWithPath:API_CREDITOR_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        NSLog(@"response: %@",responseModel);
        if (responseModel.status == ResponseSuccess) {
            weakSelf.financeListModel = [MNDFinanceListModel mj_objectWithKeyValues:responseModel.data];
            if (isPullDown) {
                [weakSelf.dataArray removeAllObjects];
            }
            [weakSelf configContents];
        }else {
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:NO reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:isPullDown];
                }];
            }
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:weakSelf.financeListModel.creditors.count];
        [self.tableView reloadData];
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData: weakSelf.dataArray.count];
    }];
    
}

- (void)configContents {
    [self.dataArray addObjectsFromArray:self.financeListModel.creditors];
    
    if (self.dataArray.count <= 0) {
        self.placeHolderMaskView.hidden = NO;
    }else {
        self.placeHolderMaskView.hidden = YES;
    }
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDCreditListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CreditCell"];
    MNDCreditorsModel *creditorsModel = self.dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.creditorsModel = creditorsModel;
    cell.progressView.progress = 0.8;
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (kScreenWidth < 414) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Detail" bundle:nil];
        
        MNDCreditorDetaiRootViewController *creditorDetailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDCreditorDetaiRootViewController"];
        MNDCreditorsModel *creditorsModel = self.dataArray[indexPath.row];
        creditorDetailVC.borrowCode = creditorsModel.borrow_code;
        creditorDetailVC.creditorCode = creditorsModel.creditor_code;
        creditorDetailVC.hidesBottomBarWhenPushed = YES;
        creditorDetailVC.discountStr = creditorsModel.discount_apr;
        [self.navigationController pushViewController:creditorDetailVC animated:YES];
    }else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDCreditorHRdetailViewController *creditorDetailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDCreditorHRdetailViewController"];
        MNDCreditorsModel *creditorsModel = self.dataArray[indexPath.row];
        creditorDetailVC.borrowCode = creditorsModel.borrow_code;
        creditorDetailVC.creditorCode = creditorsModel.creditor_code;
        creditorDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:creditorDetailVC animated:YES];
        
    }
}

#pragma mark - 无数据显示图片
- (void)creatMaskView {
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.tableView addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"哎呀~这里空空如也~";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = kColorGray;
    
    [maskView addSubview:tipLabel];
    [maskView addSubview:imgV];
    
    imgV.layer.cornerRadius = imgV.bounds.size.height*0.5;
    imgV.clipsToBounds = YES;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-80);
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(10);
    }];
    
    self.placeHolderMaskView = maskView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
